package algorithm.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 找出数组中重复的数字，如果存在返回true，否则返回false
 */
public class ContainsDuplicate {


    public static void main(String[] args) {

        int [] nums = {1,1,1,3,3,4,3,2,4,2};
        System.out.println(containsDuplicate1(nums));
    }

    //用hashmap
    public static boolean containsDuplicate(int[] nums) {

        Map<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            if (!map.containsKey(nums[i])){
                map.put(nums[i], 0);
            }else{
                return true;
            }
        }
        return false;
    }

    //先排序再两两比对
    public static boolean containsDuplicate1(int[] nums) {

        Arrays.sort(nums);

        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] == nums[i+1]){
                return true;
            }
        }
        return false;
    }
}
